package com.person.jiaiplan.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class DateUtils {

    /**
     * 从时间数组中选取当前时间后最近的一个时间点，并输出
     *
     * @param timeList
     * @return
     */
    public static String getNextTime(String[] timeList) {
        DateTime now = DateUtil.date();
        DateTime needTime = null;
        for (int i = 0; i < timeList.length; i++) {

            DateTime dateTime = DateUtil.parse(timeList[i], "yyyy-MM-dd");
            if (dateTime.isAfter(now)) {
                if (needTime == null) {
                    needTime = dateTime;
                } else {
                    if (dateTime.isBefore(needTime)) {
                        needTime = dateTime;
                    }
                }
            }
        }

        return DateUtil.format(needTime, "yyyy-MM-dd");
    }

    /**
     * 根据每周日期
     * 获取接下来一个月的计划日期数组
     *
     * @return
     */
    public static String[] getPlanDate(Date starTime, Date endTime, String[] weekDays) {

        List<String> planDate = new LinkedList<>();
        // 计算startTime 和 endTime 相差多少天
        Long betweenDay = DateUtil.betweenDay(starTime, endTime, true);

        for (int i = 0; betweenDay >= 0; betweenDay--) {
            DateTime nextDay = DateUtil.offsetDay(starTime, i);
            i++;
            Integer dayOfWeek = DateUtil.dayOfWeek(nextDay);
            // 判断是否是指定的星期
            if (Arrays.stream(weekDays).anyMatch(item -> dayOfWeek.equals(Integer.valueOf(item)))) {
                planDate.add(DateUtil.format(nextDay, "yyyy-MM-dd"));
            }
        }

        return planDate.toArray(new String[planDate.size()]);

    }

    /**
     * 根据间隔天数
     * 获取接下来一个月的计划日期数组
     *
     * @return
     */
    public static String[] getPlanDateByIntervals(Date starTime, Date endTime, Integer intervals) {
        List<String> planDate = new LinkedList<>();
        // 计算startTime 和 endTime 相差多少天
        Long betweenDay = DateUtil.betweenDay(starTime, endTime, true);
        for (int i = 0; betweenDay >= 0; betweenDay -= intervals) {
            DateTime nextDay = DateUtil.offsetDay(starTime, i);
            i = i + intervals;
            planDate.add(DateUtil.format(nextDay, "yyyy-MM-dd"));
        }
        return planDate.toArray(new String[planDate.size()]);
    }
}
